# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import MFRC522
import signal

continue_reading = True

def end_read(signal,frame):
    global continue_reading
    print "Ctrl+C captured, ending read."
    continue_reading = False
    GPIO.cleanup()

signal.signal(signal.SIGINT, end_read)

MIFAREReader = MFRC522.MFRC522()

# Welcome message
print "Welcome to the MFRC522 data read example"
print "Press Ctrl-C to stop."
card_UID = ""
def RfRead():
    # 寻卡    
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

    # 寻卡成功
    # if status == MIFAREReader.MI_OK:
    #     # print "寻卡成功！"
    
    # 获取卡片ID
    (status,uid) = MIFAREReader.MFRC522_Anticoll()

    # 判断UID是否读取成
    if status == MIFAREReader.MI_OK:
        # 输出UID
        card_UID = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])
        # print "卡号: %s" % (uid[0]+uid[1]+uid[2]+uid[3])
    
        # 默认密钥
        key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
        
        # 读取卡片
        MIFAREReader.MFRC522_SelectTag(uid)

        # 密钥验证
        status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

        # 验证成功
        if status == MIFAREReader.MI_OK:
            rfdata =  MIFAREReader.MFRC522_Read(8)
            MIFAREReader.MFRC522_StopCrypto1()
            return rfdata
        else:
            print "Authentication error"

card_data = []
bdata = []

default_person = [1]
default_book = [2]

for i in range(15):
    default_person.append(0)
    default_book.append(0)

while continue_reading:
    card_data = RfRead()
    if card_data:
        if card_data[1] == 0:
            pass
        if card_data[1] == 1:
            print("请选择借书人：")
            while True:
                bdata = RfRead()
                if bdata:
                    if bdata[1] == 2:
                        print("借书成功！")
                        continue_reading = False
                        break; 
        if card_data[1] == 2:
            print("开门成功！")
            continue_reading = False
            

